package com.bobi.tfca.ui.common

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.constants.CodeCategoryEnum
import com.bobi.tfca.databinding.FragmentEmailCheckBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MemberAPI
import com.bobi.tfca.network.api.ResourceAPI
import com.bobi.tfca.network.response.MemberProfileResponse
import com.bobi.tfca.util.LogUtil
import com.wynsbin.vciv.VerificationCodeInputView
import com.wynsbin.vciv.VerificationCodeInputView.OnInputListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


class EmailCheckFragment : BaseFragment<FragmentEmailCheckBinding, ViewModel>(
    FragmentEmailCheckBinding::inflate,
    null,
    true
) {

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentEmailCheckBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置topPanel
        setTopPanelStyle(binding)
        val codeCategory = publicViewModel!!.codeCategory

        // 发送验证码请求
        val tvEmail = binding.tvEmail
        sendEmailCode(tvEmail)


        // 设置验证码监听
        val view: VerificationCodeInputView = binding.vcivCode
        view.setOnInputListener(object : OnInputListener {
            override fun onComplete(code: String) {

                when (codeCategory) {
                    CodeCategoryEnum.REGISTER_CODE -> {
                        val member = publicViewModel?.memberProfile
                        if (member != null) {
                            registerMember(member, code)
                        } else {
                            LogUtil.e("用户对象为空")
                        }
                    }

                    CodeCategoryEnum.RESET_PASSWORD_CODE -> {
                        val account = publicViewModel?.account
                        val newPassword = publicViewModel?.newPassword
                        if (account.isNullOrBlank() || newPassword.isNullOrBlank()) {
                            LogUtil.e("用户和密码为空")
                        } else {
                            resetPassword(account, newPassword, code)
                        }
                    }

                    else -> LogUtil.e("验证码用途为空")
                }
            }

            override fun onInput() {}
        })
        // 清除验证码
        view.clearCode()
    }

    private fun sendEmailCode(tvEmail: TextView) {
        val codeCategory = publicViewModel!!.codeCategory
        when (codeCategory) {
            CodeCategoryEnum.REGISTER_CODE -> {
                val member = publicViewModel?.memberProfile
                if (member != null) {
                    tvEmail.text = member.email
                    requestServerSendCode(member.telephone, member.email)
                } else {
                    LogUtil.e("用户对象为空")
                }
            }

            CodeCategoryEnum.RESET_PASSWORD_CODE -> {
                val account = publicViewModel?.account
                val newPassword = publicViewModel?.newPassword
                if (account.isNullOrBlank() || newPassword.isNullOrBlank()) {
                    LogUtil.e("用户和密码为空")
                } else {
                    tvEmail.text = publicViewModel!!.resetEmail
                    requestServerSendCode(account)
                }
            }

            else -> LogUtil.e("验证码用途为空")
        }
    }

    private fun requestServerSendCode(account: String, email: String) {
        publicViewModel!!.apply {
            request(ResourceAPI::class.java).sendEmailCode4Register(account, email).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val res = it.data
                                if (res?.code == 200) {
                                    LogUtil.i("发送邮箱验证码成功！")
                                } else {
                                    Toast.makeText(requireActivity(), res?.msg, Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun requestServerSendCode(account: String) {
        publicViewModel!!.apply {
            request(ResourceAPI::class.java).sendEmailCode2Exist(account).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val res = it.data
                                if (res?.code == 200) {
                                    LogUtil.i("发送邮箱验证码成功！")
                                } else {
                                    Toast.makeText(requireActivity(), res?.msg, Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun resetPassword(account: String, newPassword: String, code: String) {
        publicViewModel!!.apply {
            request(MemberAPI::class.java).resetPassword(account, newPassword, code).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val code = it.data?.code
                                if (code == 200) {
                                    // 重置用途和用户和密码
                                    resetResetPasswordInfo()
                                    // 跳转回复界面
                                    requireActivity().findNavController(R.id.app_nav).navigate(
                                        R.id.action_emailCheckFragment_to_replyFragment, null,
                                        NavOptions.Builder()
                                            .setPopUpTo(R.id.forgetPasswordFragment, true)
                                            .build()
                                    )
                                    Toast.makeText(requireActivity(), "修改密码成功", Toast.LENGTH_SHORT).show()
                                } else {
                                    Toast.makeText(requireActivity(), it.data?.msg, Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun registerMember(member: MemberProfileResponse, code: String) {
        publicViewModel!!.apply {
            request(MemberAPI::class.java).registerMember(member, code).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }
                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val code = it.data?.code
                                if (code == 200) {
                                    // 重置用途和文档对象
                                    resetRegisterInfo()
                                    // 跳转回复界面
                                    requireActivity().findNavController(R.id.app_nav).navigate(
                                        R.id.action_emailCheckFragment_to_replyFragment, null,
                                        NavOptions.Builder()
                                            .setPopUpTo(R.id.registerMemberFragment, true)
                                            .build()
                                    )
                                    Toast.makeText(requireActivity(), "注册成功", Toast.LENGTH_SHORT).show()
                                } else {
                                    Toast.makeText(requireActivity(), it.data?.msg, Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentEmailCheckBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.visibility = View.GONE
    }

}